<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%-- 引入公用JSP --%>
<%@ include file="/WEB-INF/include/taglib.jsp"%>
<%-- 加入自定义UI标签库 --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- EasyUI -->
<link rel="stylesheet" type="text/css" href="${pageScope.staticPath}/jQueryEasyUI/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${pageScope.staticPath}/jQueryEasyUI/themes/icon.css">
<link rel="stylesheet" type="text/css" href="${pageScope.staticPath}/jQueryEasyUI/themes/ExpandIcon.css">
<script type="text/javascript" src="${pageScope.staticPath}/jQueryEasyUI/jquery.min.js"></script>
<script type="text/javascript" src="${pageScope.staticPath}/jQueryEasyUI/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${pageScope.staticPath}/jQueryEasyUI/locale/easyui-lang-zh_CN.js"></script>
<!-- jQuery-File-Upload -->
<script type="text/javascript" src="${staticPath}/JQueryPlugin/jQuery-File-Upload/jquery.ui.widget.js"></script>
<script type="text/javascript" src="${staticPath}/JQueryPlugin/jQuery-File-Upload/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="${staticPath}/JQueryPlugin/jQuery-File-Upload/jquery.fileupload.js"></script>
<!-- CryptoJS -->
<script type="text/javascript" src="${staticPath}/CryptoJS/rollups/md5.js"></script>
<script type="text/javascript" src="${staticPath}/CryptoJS/components/lib-typedarrays-min.js"></script>
<title>系统模版管理</title>
<style type="text/css">
.row {
	margin-bottom: 8px;
}
.row label {
	display: inline-block;
	width: 60px;
	text-align: center;
}
.row input,select {
	width: 160px;
}
.row .column {
	margin-right: 10px;
}
.row .columnLast {
	margin-right: 0px;
}
</style>
</head>
<body class="easyui-layout" data-options="fit:true,border:false">
	<!-- 页面上部 -->
	<div data-options="region:'north',border:true" style="height:70px;">
		<form id="fm-search" method="post" style="margin-top: 5px;margin-left: 20px">
			<div class="row">
				<span class="column">
					<label for="search_name">模版名称</label> 
					<input id="search_name" name="name" class="easyui-textbox">
				</span>
				<span class="columnLast">
					<label for="search_fileName">模版文件名</label> 
					<input id="search_fileName" name="fileName" class="easyui-textbox" style="width: 410px">
				</span>
			</div>
			<div class="row">
				<span class="column">
					<label for="search_id">数据ID</label>
					<input id="search_id" name="id" class="easyui-textbox">
				</span>
				<span class="columnLast">
					<label for="search_uuid">数据UUID</label> 
					<input id="search_uuid" name="uuid" class="easyui-textbox" style="width: 410px">
				</span> 
			</div>
		</form>
	</div>

	<!-- 页面中部 -->
	<div id="centerPanel" data-options="region:'center',border:false">
		<table id="templateFileData" data-options="border:false">
			<thead>
				<tr>
					<th data-options="field:'name',width:200,align:'left'">模版名称</th>
					<th data-options="field:'fileinfo_id',width:150,align:'left',hidden:true">上传文件信息表ID</th>
					
					<th data-options="field:'b_file_name',width:200,align:'left',hidden:false,formatter:fileNameFormatter">文件名称</th>
					<th data-options="field:'b_file_size',width:80,align:'left',hidden:false,formatter:fileSizeFormatter">文件大小</th>
					<th data-options="field:'b_update_date',width:130,align:'left',hidden:false,formatter:formatDate">文件更新时间</th>
					
					<th data-options="field:'id',width:30,align:'left',hidden:true">编号</th>
					<th data-options="field:'company_id',width:80,align:'left',hidden:true">所属公司的编码</th>
                    <th data-options="field:'org_id',width:80,align:'left',hidden:true">所属机构的编码</th>
					<th data-options="field:'create_by',width:50,align:'left',hidden:true">创建者</th>
					<th data-options="field:'create_date',width:100,align:'left',hidden:true">创建时间</th>
					<th data-options="field:'update_by',width:50,align:'left',hidden:true">更新者</th>
					<th data-options="field:'update_date',width:100,align:'left',hidden:true">更新时间</th>
					<th data-options="field:'remarks',width:200,align:'left'">备注信息</th>
					<th data-options="field:'del_flag',width:50,align:'left',hidden:true">删除标记</th>
					<th data-options="field:'uuid',width:80,align:'left',hidden:true">数据UUID</th>
				</tr>
			</thead>
		</table>
		<div id="tb">
			<a onclick="searchTemplateFile();" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-search',plain:true">查询</a>
			<a onclick="newTemplateFile();" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true">新增</a>
			<a onclick="editTemplateFile();" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-edit',plain:true">编辑</a>
			<a onclick="delTemplateFile();" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true">删除</a>
	    </div>
	</div>

	<!-- 新增/编辑对话框 -->
	<div id="dlg" style="width: 520px; height: 260px; padding: 5px 10px">
	
		<form id="fm" method="post">
			<div class="row" style="margin-top: 10px;">
				<span class="columnLast">
					<label for="dialog_name">模版名称</label> 
					<input id="dialog_name" name="name" class="easyui-textbox" style="width: 410px">
				</span>
			</div>
			<div class="row">
				<span class="columnLast"> 
					<label for="dialog_remarks">备注信息</label> 
					<input id="dialog_remarks" name="remarks" style="width:410px;height:40px">
				</span>
			</div>
			
			<!-- 隐藏属性值 -->
			<div style="display: none;">
				<input id="fileinfoId" name="fileinfoId">
				<input name="id">
				<input name="delFlag">
				<input name="companyId">
				<input name="orgId">
				<input name="createBy">
				<input name="createDate">
				<input name="updateBy">
				<input name="updateDate">
				<input name="uuid">
			</div>
		</form>
		
		<div class="row" style="margin-top: 25px;">
			<span id="span_fileupload" class="columnLast">
				<label>模板文件</label> 
				<input id="fileupload" type="file" name="templateFile" style="width: 410px">
			</span>
		</div>
		
		<div style="margin-top: 5px;margin-bottom: 2px;">
			<span style="margin-left: 5px;">
				<label>模板文件上传状态：</label>
				<label id="uploadMsg" style="text-align: left;" ></label>
			</span>
			<div id="progressbar" style="margin-top: 2px;"></div>
		</div>
	</div>
	<div id="dlg-buttons">
		<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" onclick="saveClick();" style="width:90px">保存</a>
		<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-cancel'" onclick="javascript:$('#dlg').dialog('close')" style="width:90px">取消</a>
	</div>

	<script type="text/javascript">
	// 获取分页TemplateFile数据地址
	var findTemplateFileByPageUrl = "${pageScope.mvcPath}/sys/findTemplateFileByPage";
	// 增加TemplateFile数据
	var addTemplateFileUrl = "${pageScope.mvcPath}/sys/addTemplateFile";
	// 更新TemplateFile数据
	var updateTemplateFileUrl = "${pageScope.mvcPath}/sys/updateTemplateFile";
	// 删除TemplateFile数据
	var deleteTemplateFileUrl = "${pageScope.mvcPath}/sys/deleteTemplateFile";
	var saveTemplateFileUrl;
	// 秒传文件地址
	var uploadLazyUrl = "${pageScope.mvcPath}/fileupload/uploadLazy"
	// 文件上传地址
	var uploadUrl = "${pageScope.mvcPath}/fileupload/upload";
    // 下载文件地址. url + 文件UUID
    var downloadFileUrl = "${pageScope.mvcPath}/fileupload/fileDownload/";
    
	$(document).ready(function () {
		
		// 设置templateFileData数据显示表格
		$("#templateFileData").datagrid({
			url : findTemplateFileByPageUrl,
			idField : "id",
			fit : true,
			fitColumns : false,
			striped : true,
			rownumbers : true,
			singleSelect : true,
			nowrap : true,
			pagination : true,
			loadMsg : "正在加载，请稍候...",
			toolbar : "#tb",
			onDblClickRow : function (rowIndex, rowData) {
				editTemplateFile();
			},
			onBeforeLoad : function (param) {
				// 增加查询参数
				var paramArray = $("#fm-search").serializeArray();
				$(paramArray).each(function () {
					if (param[this.name]) {
						if ($.isArray(param[this.name])) {
							param[this.name].push(this.value);
						} else {
							param[this.name] = [param[this.name], this.value];
						}
					} else {
						param[this.name] = this.value;
					}
				});
			}
		});
		
		$("#dlg").dialog({
			title : "模板文件",
			closed : true,
			resizable : true,
			minWidth : 520,
			minHeight : 260,
			maxWidth : 520,
			maxHeight : 260,
			modal : true,
			buttons : "#dlg-buttons",
			onOpen : function() {
				$("#fileupload").val("");
				$("#uploadMsg").html("");
				$("#progressbar").progressbar("setValue", 0);
			}
		});
		
		$("#dialog_name").textbox({
			required : true,
			readonly : false,
			validType : 'length[1,100]',
		});
		
		$("#dialog_remarks").textbox({
			validType : 'length[3,255]',
			multiline:true
		});
		
		$("#progressbar").progressbar({
			width : "100%",
			height : 15,
			value : 0,
			text : "文件上传进度:{value}%"
		});
		
		// 判断浏览器是否支持读取文件
		if(canReadFile() == false) {
			$.messager.alert("提示", "您的浏览器不支持读取文件，这会影响上传文件速度，建议使用最新的浏览器!", "warning");
		}
	});
	
	// 保存按钮事件
	function saveClick() {
		var uploadFiles = getUploadFiles();
		if( uploadFiles.length <=0 ){
			$("#uploadMsg").html("<span style='color: red;'>请选择模版文件</span>");
			$("#fileupload").focus();
			return ;
		}
		$("#uploadMsg").html("");
		if($("#fm").form("validate") == false) {
			return ;
		}
		// 上传文件，保存模版
		fileupload();
	}
	
	// 保存模版数据
	function saveTemplateFile(fileinfoId) {
		$("#fileinfoId").val(fileinfoId);
		
		// 保存模版数据
		$("#fm").form("submit", {
			url : saveTemplateFileUrl,
			success : function (data) {
				var data = $.parseJSON(data);
				if (data.success) {
					// 保存成功
					$('#dlg').dialog('close')
					$.messager.show({ title : '提示', msg : data.message, timeout : 5000, showType : 'slide' });
					$("#templateFileData").datagrid('reload');
				} else {
					// 保存失败
					$.messager.alert("提示", data.message, "warning");
				}
			}
		});
	}
	
	// 查询模版数据
	function searchTemplateFile() {
		$("#templateFileData").datagrid('load');
	}

	// 新增模版
	function newTemplateFile() {
		saveTemplateFileUrl = addTemplateFileUrl;
		$('#dlg').dialog('open').dialog('setTitle', '新增模版');
		$('#fm').form('reset');
	}

	// 编辑模版
	function editTemplateFile() {
		saveTemplateFileUrl = updateTemplateFileUrl;
		var row = $('#templateFileData').datagrid("getSelected");
		row = dataRowConvert(row);
		if (row == null) {
			$.messager.alert("提示", "未选择要编辑的数据！", "info");
			return;
		}
		if (row) {
			$('#dlg').dialog('open').dialog('setTitle', '编辑模版');
			$('#fm').form('load', row);
		}
	}

	// 删除模版
	function delTemplateFile() {
		var row = $("#templateFileData").datagrid("getSelected");
		row = dataRowConvert(row);
		if (row == null) {
			$.messager.alert("提示", "未选择要删除的数据！", "info");
			return;
		}
		$.messager.confirm("确认删除", "确定要删除模版?<br/>模版名称：" + row.name, function (r) {
			if (r) {
				$.post(deleteTemplateFileUrl, row, function (data) {
					if (data.success) {
						// 删除成功
						$.messager.show({ title : '提示', msg : data.message, timeout : 5000, showType : 'slide' });
						$("#templateFileData").datagrid('reload');
					} else {
						// 删除失败
						$.messager.alert("提示", data.message, "warning");
					}
				}, "json");
			}
		});
	}
	
	// 数据转换
	function dataRowConvert(row)
	{
		if(row == null) {
			return null;
		}
		var newRow = {};
		newRow.id = row.id;
		newRow.companyId = row.company_id;
		newRow.orgId = row.org_id;
		newRow.createBy = row.create_by;
		newRow.createDate = new Date(row.create_date).format("yyyy-MM-dd hh:mm:ss");
		newRow.updateBy = row.update_by;
		newRow.updateDate = new Date(row.update_date).format("yyyy-MM-dd hh:mm:ss");
		newRow.remarks = row.remarks;
		newRow.delFlag = row.del_flag;
		newRow.uuid = row.uuid;
		newRow.fileinfoId = row.fileinfo_id;
		newRow.name = row.name;
		return newRow;
	}
	
	// 上传文件
	function fileupload() {
		if(canReadFile() == true) {
			// 计算文件签名
			var file = getUploadFiles()[0];
	   		var md5Hash = CryptoJS.algo.MD5.create();
	   		readFile(
				file,
				function(chunks, currentChunk, e) {
					var array = new Uint8Array(e.target.result);
					var data = CryptoJS.lib.WordArray.create(array);
					md5Hash.update(data);
					var progress = parseInt(currentChunk * 100 / chunks, 10);
					$("#uploadMsg").text("正在计算文件签名(" + progress + "%)");
				},
				function (md5) {
					var md5 = md5Hash.finalize().toString(CryptoJS.enc.Hex);
					$("#uploadMsg").text("开始秒传文件...");
					// 使用秒传功能
					var param = {};
					param.fileName = file.name;
					param.fileDigest = md5;
					param.digestType = "MD5";
					$.post(uploadLazyUrl, param, function (data){
						if(data.success == true){
							$("#uploadMsg").text("秒传成功");
							$("#progressbar").progressbar("setValue", 100);
							// 保存模版数据
							saveTemplateFile(data.object.id);
						} else {
							$("#uploadMsg").text("秒传失败,开始上传文件...");
							uploadToLocal();
						}
					}, "json");
				}
			);
		} else {
			// 直接上传文件
			uploadToLocal();
		}
	}
	
	// 真正的上传文件
	function uploadToLocal() {
		$("#fileupload").fileupload({
			url : uploadUrl,
			type : "POST",
			dataType : "json",
			autoUpload : false,
			progress : function (e, data) {
				var progress = parseInt(data.loaded / data.total * 100, 10);
				$("#progressbar").progressbar("setValue", progress);
			},
			done : function (e, data) {
				$("#uploadMsg").text("文件上传成功");
				// 保存模版数据
				saveTemplateFile(data.result.object[0].id);
			},
			fail : function (e, data) {
				$.messager.alert("提示","模板文件上传失败!","error");
			},
			always : function (e, data) {
				//设置 autoUpload : false 不需要
				$("#fileupload").fileupload("destroy");
			}
	    });
		
		var jqXHR = $("#fileupload").fileupload("send", {
			files : getUploadFiles()[0]
		}).error(function (jqXHR, textStatus, errorThrown) {
			if (errorThrown === "abort") {
				$.messager.alert("提示","模板文件上传已取消!","warning");
			}
		});
	}
	
	// 返回选择的所有文件对象，不同浏览器取值方式不同
	function getUploadFiles() {
		var uploadFiles = $("#fileupload").prop("files");
		if(typeof uploadFiles == "undefined") {
			uploadFiles = $("#fileupload");
		}
		if(uploadFiles.hasOwnProperty("length") && uploadFiles.length >= 1) {
			if($.trim(uploadFiles[0].value) == "") {
				uploadFiles = [];
			}
		}
		return uploadFiles;
	}
	
	// 用于判断浏览器是否支持读取文件
    function canReadFile() {
        try {
            // Check for FileApi
            if (typeof FileReader == "undefined") {
            	return false;
            }
            // Check for Blob and slice api
            if (typeof Blob == "undefined") {
            	return false;
            }
            var blob = new Blob();
            if (!blob.slice && !blob.webkitSlice) {
            	return false;
            }
        } catch (e) {
            return false;
        }
        return true;
    }
	
	// 读取文件
	function readFile(file, work, callback) {
		// 文件读取对象 HTML5
		var fileReader = new FileReader();
		// 分割文件对象
		var blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice
		// 文件块大小 1MB
		var chunkSize = 1 * 1024 * 1024;
		var chunks = Math.ceil(file.size / chunkSize);
		var currentChunk = 0;
		//每块文件读取完毕之后的处理
		fileReader.onload = function (e) {
			currentChunk++;
			var workResult = work(chunks, currentChunk, e);
			if (currentChunk < chunks) {
				// 继续读取文件
				loadNext();
			} else {
				// 文件读取完成
				callback(workResult);
			}
		};
		// 读取下一个文件块
		function loadNext() {
			var start = currentChunk * chunkSize;
			var end = start + chunkSize >= file.size ? file.size : start + chunkSize;
			var blob = file.slice(start, end);
			fileReader.readAsArrayBuffer(blob);
		}
		loadNext();
	}
	
    function fileSizeFormatter(value,row,index){
    	var sizeByte = value;
    	var sizeKB = (sizeByte / 1024.0).toFixed(2);
    	if(sizeKB < 1){
    		return sizeByte + "B";
    	}
    	
    	var sizeMB = (sizeKB / 1024.0).toFixed(2);
    	if(sizeMB < 1){
    		return sizeKB + "KB";
    	}
    	
    	var sizeGB = (sizeMB / 1024.0).toFixed(2);
    	if(sizeGB < 1){
    		return sizeMB + "MB";
    	}
    	return sizeGB + "GB";
    }
    
    function fileNameFormatter(value,row,index){
    	var url = downloadFileUrl + row.b_uuid;
    	return "<a target='_blank' href='" + url + "'>" + value + "</a>";
    }
    
    function formatDate(value,row,index) {
    	var date = new Date(value);
    	return date.format("yyyy-MM-dd hh:mm:ss");
    }
    
    // 日期格式化
    Date.prototype.format = function (fmt) {
    	var o = {
    		"M+" : this.getMonth() + 1, //月份
    		"d+" : this.getDate(), //日
    		"h+" : this.getHours(), //小时
    		"m+" : this.getMinutes(), //分
    		"s+" : this.getSeconds(), //秒
    		"q+" : Math.floor((this.getMonth() + 3) / 3), //季度
    		"S" : this.getMilliseconds() //毫秒
    	};
    	if (/(y+)/.test(fmt)){
    		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    	}
    	for (var k in o) {
    		if (new RegExp("(" + k + ")").test(fmt)) {
    			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    		}
    	}
    	return fmt;
    }
	</script>
</body>
</html>